package com.bucg.cjcloud.gb28181.sip.handler;

import cn.hutool.core.collection.ConcurrentHashSet;
import com.bucg.cjcloud.gb28181.media.cache.PlayCache;
import com.bucg.cjcloud.gb28181.common.entity.ItemEntity;
import com.bucg.cjcloud.gb28181.common.entity.PlatformEntity;
import com.bucg.cjcloud.gb28181.sip.xmlbean.XmlUtils;
import com.bucg.cjcloud.gb28181.common.repository.ItemRepository;
import com.bucg.cjcloud.gb28181.common.repository.PlatformRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sip.header.ViaHeader;
import javax.sip.message.Request;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

/**
 * RegisterHandlerImpl..
 *
 * @author Lizhong
 * @date 2020/3/5
 */

@Component
public class RegisterHandlerImpl implements RegisterHandler {
    private  Set<String> isRegisted =new ConcurrentHashSet<>();
    @Autowired
    PlatformRepository platformRepository;
    @Autowired
    ItemRepository itemRepository;



    @Override
    public void handler(Request req, String deviceId) {
        // 获取设备真实地址
        ViaHeader via = (ViaHeader) req.getHeader(ViaHeader.NAME);
        String realIp = via.getReceived();
        int realPort = via.getRPort();

        if (isRegisted.contains(deviceId)) return;

        PlatformEntity byDeviceID = platformRepository.findByDeviceId(deviceId);
        if (byDeviceID != null) return;

        PlatformEntity platform = new PlatformEntity(deviceId, LocalDateTime.now(), realIp + ":" + realPort);
        platform.setDeviceId(deviceId);

        // 是否做判重处理

        // FIXME: 2020/3/6 判重处理
        // List<PlatformEntity> platforms = platformRepository.findAll(Example.of(platform,
        //         ExampleMatcher.matching()
        //                 .withMatcher("deviceId", ExampleMatcher.GenericPropertyMatcher::exact)
        //                 .withMatcher("realAddr", ExampleMatcher.GenericPropertyMatcher::exact)));
        // if (platforms.size() > 1)


        platformRepository.save(platform);
        isRegisted.add(deviceId);
        byte[] rawContent = req.getRawContent();
        if (rawContent == null) return;
        String source = new String(rawContent);
        List<ItemEntity> deviceList = XmlUtils.getDeviceList(source);
        if (deviceList.size() > 0) {
            deviceList.forEach(val -> val.setSsrcId(PlayCache.genSsrcId()));
            itemRepository.saveAll(deviceList);
        }

    }

    public  Set<String> getIsRegisted() {
        return isRegisted;
    }
}
